package initialize

import (
	"a_plus_station/global"
	"a_plus_station/models"
	"context"
	"fmt"
	jsoniter "github.com/json-iterator/go"
	"github.com/olivere/elastic/v7"
	"go.uber.org/zap"
	"log"
	"os"
)

func InitEs() {
	EsConfig := global.ServerConfig.EsConfig
	url := fmt.Sprintf("http://%s:%d/", EsConfig.Host, EsConfig.Port)
	logger := log.New(os.Stdout, "a_plus_station", log.LstdFlags)

	var err error
	global.EsClient, err = elastic.NewClient(elastic.SetURL(url), elastic.SetSniff(false), elastic.SetTraceLog(logger))
	if err != nil {
		zap.S().Info("初始化EsClient失败:", err)
	}

	//新建index和mapping
	//先查询index是否存在
	esModel := models.EsGoods{}
	exists, err := global.EsClient.IndexExists(esModel.GetIndexName()).Do(context.Background())
	if err != nil {
		panic(err)
	}

	aa := esModel.GetMapping()
	mar, err := jsoniter.Marshal(aa)
	if err != nil {
		panic("mapping 错误")
	}
	fmt.Println(mar)
	//新建索引和mapping
	if !exists {
		createIndex, err := global.EsClient.CreateIndex(esModel.GetIndexName()).BodyString(esModel.GetMapping()).Do(context.Background())
		if err != nil {
			panic(err)
		}
		if !createIndex.Acknowledged {
			panic("创建失败")
		}
		fmt.Println("index 创建成功")
		global.EsIndexExists = true
	}

}
